<?php
defined('_XR_EXEC') or die();
/**
 * test module
 */
class trans_model extends model
{ 
	public function __construct() {
		parent::__construct();
	}
	/* 获取余额 */
  public function getbalance($user_id){
		$db = factory::getDBO();
		return $db->loadresult('select balance from t_user where id="'.intval($user_id).'" ');
	}
	
	 
	public function add_byslug($transtype_slug='',$user_id=0,$fee=0,$remark='',$created_user_id='1',$created_ip='',$ifenough=true,$order_id=0){
		$transtype_id = '0';
		$db = factory::getdbo();
		$transtype_id = $db->loadresult('select id from `#__transtype` where active=1 and slug="'.$transtype_slug.'" ');
		if(!$transtype_id){
			$this->setErrorNum('10');
			$this->setError('账户事务类别不存在，或事务未激活');
			return false;
		}
		return $this->add($transtype_id,$user_id,$fee,$remark,$created_user_id,$created_ip,$ifenough,$order_id);
	}
	
	public function add($transtype_id,$user_id,$fee,$remark='',$created_user_id='1',$created_ip='',$ifenough=true,$order_id='0'){
		$db = factory::getDBO();
		$db->begin(); 
		$actions = $db->loadresult('select actions from `#__transtype` where active=1 and id="'.intval($transtype_id).'"  ');
		if($actions === false){
			$db->rollback();
			$this->setErrorNum('10');
			$this->setError('账户事务类别不存在，或事务未激活');
			return false;
		}
		if($actions == '-'){
			$fee = abs($fee) * -1;
		}else{
			$fee = abs($fee);
		}
		/* 余额判断 */
		if($ifenough === true){
			if($this->getbalance($user_id) + $fee < 0 ){
				$db->rollback();
				$this->setErrorNum('20');
				$this->setError('会员账户余额不足');
				return false;
			}
		}	
	  # 更新余额
		if(!$db->query('update t_user set balance=balance+'.$fee.' where id="'.$user_id.'"') ){
			$db->rollback();
			$this->setErrorNum('30');
			$this->setError('更新余额失败');
			return false;
		}
		/* 插入消费数据 */
		$trans_id = $db->insert('trans',array(
			'transtype_id'=>$transtype_id,
			'user_id'=>$user_id, 
			'fee'=>($fee*-1),
			'balance'=>$this->getbalance($user_id),
			'remark'=>$remark, 
			'created'=>'now()',
			'created_user_id'=>$created_user_id,
			'created_ip'=>$created_ip,
			'order_id'=>$order_id
		));
		if(!$trans_id){
			$db->rollback();
			$this->setErrorNum('40');
			$this->setError('系统繁忙，请稍后重试');
			return false;
		}
		$db->commit();
		return $trans_id;
	}
}

?>